<!--
  文件描述：
  创建时间：2023/9/7 13:06
  创建人：二
-->
<template>
  <m-dialog
    :title="title"
    :visible="visible"
    width="500px"
    :show-close="true"
    :loading="loading"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="img">
        <m-select-image
          v-model="form.img"
          :default-list="defaultList"
        />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="close" :disabled="loading">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()" :loading="loading">确 定</el-button>
    </template>
  </m-dialog>
</template>

<script>
import MSelectImage from '@/components/MSelectImage/MSelectImage'
export default {
  name: 'UserAdd',
  components: {MSelectImage},
  data() {
    return {
      type: '', // 打开页面类型
      visible: false,
      loading: false,
      form: {
        name: '',
        email: '',
        img: ''
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入用户名称' }
        ],
        email: [
          { required: true, trigger: 'blur', message: '请输入邮箱' }
        ],
        img: [
          { required: true, trigger: 'change', message: '请上传头像' }
        ]
      },
      defaultList: [
        {
          id: 12,
          path: 'https://fastly.picsum.photos/id/317/400/800.jpg?hmac=36uD390dff3ss3t3rQVST-GqedHWHH49pqd-bepm6M8'
        }
      ]
    }
  },
  computed: {
    title() {
      return this.type ? '新增' : '编辑'
    }
  },
  methods: {
    // 打开
    open(type = 'add', data) {
      this.type = type;
      if(type === 'edit') {
        this.form = this.mixinObjAssign(this.form, data);
      }
      this.visible = true;
    },
    // 关闭
    close() {
      this.loading = false;
      this.resetSearchForm();
      this.visible = false;
    },
    // 重置表单
    resetSearchForm() {
      this.$refs.form.resetFields();
    },
    // 提交
    handleSubmit() {
      this.$refs.form.validate( valid => {
        if(valid) {
          this.mixinMessageBoxConfirm('是否提交保存?').then(({instance, done}) => {
            this.loading = true;
            setTimeout(() => {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
                this.$message({
                  type: 'success',
                  message: '成功!'
                });
                this.close();
                this.$emit('success', this.type === 'add');
              }, 300);
            }, 2000);
          }).catch(() => {})
        }
        return false
      })
    }
  }
}
</script>

<style scoped>

</style>
